# -*- coding: utf-8 -*-
import re
from django.contrib.auth.models import AnonymousUser
from rest_framework.permissions import BasePermission
from typing import Any, List
from rest_access_policy import AccessPolicy
from apps.sys.models import WhiteList


class AnonymousUserPermission(BasePermission):
    """
    匿名用户权限
    """

    def has_permission(self, request, view):
        if isinstance(request.user, AnonymousUser):
            return False
        return True


class CustomPermission(AccessPolicy):
    """自定义权限"""

    id_prefix = "id:"
    group_prefix = "role:"

    def has_permission(self, request, view):
        user = request.user

        # 检查是否为匿名用户
        if isinstance(user, AnonymousUser):
            return False

        # 检查是否为超级管理员
        if user.is_superuser:
            return True

        # 检查特定视图方法的权限
        is_head = getattr(view, "head", None)
        if (
            is_head
            and hasattr(is_head, "kwargs")
            and "permission_classes" in is_head.kwargs
        ):
            permission_classes = is_head.kwargs["permission_classes"]
            if permission_classes is None:
                return True

        # 检查用户角色属性
        if not hasattr(request.user, "roles"):
            return False

        # 检查白名单权限设置
        regex_cache = {}
        white_list = WhiteList.objects.values("url", "method")
        request_api = f"{request.path}:{request.method}"
        for item in white_list:
            url_pattern = item["url"].replace("{id}", ".*?") + ":" + str(item["method"])
            if url_pattern not in regex_cache:
                regex_cache[url_pattern] = re.compile(url_pattern, re.M | re.I)

            if regex_cache[url_pattern].match(request_api):
                return True

        return super().has_permission(request, view)

    def get_user_group_values(self, user) -> List[str]:
        return list(user.roles.values_list("key", flat=True))
